const express = require('express');
const router = express.Router();
const path = require('path');
const fs = require('fs');
const archiver = require('archiver');
const Album = require('../models/Album');
const Photo = require('../models/Photo');
const auth = require('../middleware/auth');

// 创建相册
router.post('/', auth, async (req, res) => {
  try {
    const { name, description, parentAlbum } = req.body;
    
    const album = new Album({
      name,
      description,
      user: req.user._id,
      parentAlbum: parentAlbum || null
    });

    await album.save();
    res.status(201).json(album);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

// 获取相册列表
router.get('/', auth, async (req, res) => {
  try {
    const { parentAlbum } = req.query;
    const query = {
      user: req.user._id,
      isDeleted: false,
      parentAlbum: parentAlbum || null
    };

    const albums = await Album.find(query).sort({ createdAt: -1 });
    res.json(albums);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 获取回收站相册
router.get('/trash', auth, async (req, res) => {
  try {
    const albums = await Album.find({
      user: req.user._id,
      isDeleted: true
    }).sort({ deletedAt: -1 });
    
    // 为每个相册加载其下的所有照片（包括软删除的照片）
    const albumsWithPhotos = await Promise.all(albums.map(async (album) => {
      const photos = await Photo.find({ album: album._id });
      return { ...album.toObject(), photos };
    }));
    
    res.json(albumsWithPhotos);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 更新相册
router.patch('/:id', auth, async (req, res) => {
  try {
    const { name, description } = req.body;
    const album = await Album.findOne({
      _id: req.params.id,
      user: req.user._id
    });

    if (!album) {
      return res.status(404).json({ error: '相册不存在' });
    }

    if (name) album.name = name;
    if (description) album.description = description;

    await album.save();
    res.json(album);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

// 清空回收站中的相册
router.delete('/clear-trash', auth, async (req, res) => {
  try {
    // 查找用户的所有已删除相册
    const albums = await Album.find({
      user: req.user._id,
      isDeleted: true
    });

    // 遍历相册，删除相关照片
    for (const album of albums) {
      // 查找相册中的所有已删除照片
      const photos = await Photo.find({ 
        album: album._id,
        isDeleted: true 
      });
      
      // 删除照片文件
      for (const photo of photos) {
        const filePath = path.join(__dirname, '../uploads', photo.datePath, photo.filename);
        const thumbnailPath = path.join(__dirname, '../uploads/thumbnails', photo.datePath, photo.filename);
        const previewPath = path.join(__dirname, '../uploads/previews', photo.datePath, photo.filename);
        
        try {
          if (fs.existsSync(filePath)) {
            fs.unlinkSync(filePath);
          }
          if (fs.existsSync(thumbnailPath)) {
            fs.unlinkSync(thumbnailPath);
          }
          if (fs.existsSync(previewPath)) {
            fs.unlinkSync(previewPath);
          }
        } catch (fileError) {
          console.error('删除照片文件失败:', fileError);
        }
      }

      // 删除相册中的所有已删除照片记录
      await Photo.deleteMany({ 
        album: album._id,
        isDeleted: true 
      });
    }

    // 删除所有已删除的相册记录
    const result = await Album.deleteMany({
      user: req.user._id,
      isDeleted: true
    });

    res.json({ 
      message: '回收站已清空',
      deletedCount: result.deletedCount
    });
  } catch (error) {
    console.error('清空回收站失败:', error);
    res.status(500).json({ message: '清空回收站失败: ' + error.message });
  }
});

// 永久删除相册（带确认）
router.delete('/:id/permanent', auth, async (req, res) => {
  try {
    // 验证 ID 格式
    if (!req.params.id || !/^[0-9a-fA-F]{24}$/.test(req.params.id)) {
      return res.status(400).json({ message: '无效的相册ID' });
    }

    const { confirm } = req.query;
    const album = await Album.findOne({
      _id: req.params.id,
      user: req.user._id,
      isDeleted: true
    });

    if (!album) {
      return res.status(404).json({ message: '相册不存在' });
    }

    if (!confirm) {
      // 第一次请求，返回确认提示
      return res.status(200).json({
        confirm: true,
        message: '此操作将永久删除相册及其所有照片，且不可恢复。是否确认？'
      });
    }

    // 删除相册中的所有照片
    const photos = await Photo.find({ album: album._id });
    for (const photo of photos) {
      // 删除原图、缩略图、预览图
      const filePath = path.join(__dirname, '../uploads', photo.datePath, photo.filename);
      const thumbnailPath = path.join(__dirname, '../uploads/thumbnails', photo.datePath, photo.filename);
      const previewPath = path.join(__dirname, '../uploads/previews', photo.datePath, photo.filename);
      try {
        if (fs.existsSync(filePath)) {
          fs.unlinkSync(filePath);
        }
        if (fs.existsSync(thumbnailPath)) {
          fs.unlinkSync(thumbnailPath);
        }
        if (fs.existsSync(previewPath)) {
          fs.unlinkSync(previewPath);
        }
      } catch (fileError) {
        console.error('删除照片文件失败:', fileError);
      }
    }

    // 删除相册中的所有照片记录
    await Photo.deleteMany({ album: album._id });

    // 删除相册记录
    await Album.deleteOne({ _id: album._id });

    res.json({ message: '相册已永久删除' });
  } catch (error) {
    console.error('永久删除相册失败:', error);
    res.status(500).json({ message: '删除失败: ' + error.message });
  }
});

// 恢复相册
router.post('/:id/restore', auth, async (req, res) => {
  try {
    const album = await Album.findOne({
      _id: req.params.id,
      user: req.user._id,
      isDeleted: true
    });

    if (!album) {
      return res.status(404).json({ error: '相册不存在' });
    }

    album.isDeleted = false;
    album.deletedAt = null;
    await album.save();

    // 同时恢复该相册下的所有照片
    await Photo.updateMany(
      { album: album._id },
      { isDeleted: false, deletedAt: null }
    );

    res.json({ message: '相册已恢复' });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 删除相册（软删除）
router.delete('/:id', auth, async (req, res) => {
  try {
    const album = await Album.findOne({ _id: req.params.id, user: req.user.id });
    if (!album) {
      return res.status(404).json({ message: '相册不存在' });
    }
    // 软删除相册
    album.isDeleted = true;
    album.deletedAt = new Date();
    await album.save();
    // 可选：照片也做软删除（如有需求）
    // await Photo.updateMany({ album: album._id }, { isDeleted: true, deletedAt: new Date() });
    res.json({ message: '相册已移入回收站' });
  } catch (error) {
    console.error('软删除相册失败:', error);
    res.status(500).json({ message: '删除失败' });
  }
});

// 下载相册
router.get('/:id/download', auth, async (req, res) => {
  try {
    const album = await Album.findOne({
      _id: req.params.id,
      user: req.user._id
    });

    if (!album) {
      return res.status(404).json({ error: '相册不存在' });
    }

    const photos = await Photo.find({
      album: album._id,
      user: req.user._id
    });

    if (photos.length === 0) {
      return res.status(404).json({ error: '相册中没有照片' });
    }

    const archive = archiver('zip', {
      zlib: { level: 9 } // 最高压缩级别
    });

    res.attachment(`${album.name}.zip`);
    archive.pipe(res);

    // 添加文件到压缩包
    for (const photo of photos) {
      const filePath = path.join(__dirname, '../uploads', photo.datePath, photo.filename);
      if (fs.existsSync(filePath)) {
        archive.file(filePath, { name: photo.originalName });
      }
    }

    await archive.finalize();
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

module.exports = router; 